package com.jwtproject.bootserver.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.jwtproject.bootserver.model.Role;
import com.jwtproject.bootserver.model.User;
import com.jwtproject.bootserver.security.entity.SecurityUserDetails;
import com.jwtproject.bootserver.service.RoleService;
import com.jwtproject.bootserver.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description：用户登陆信息获取
 **/
@Slf4j
@Service
@AllArgsConstructor
public class MyUsernameDetailsService extends BaseUserDetailService {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 获取用户信息
     * @param username
     * @return
     */
    @Override
    protected UserDetails getUserDetails(String username) {
        User user = null;
        try {
            //获取用户信息
            user = userService.getEmpByUsername(username);

        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("查询用户失败,原因是：" + e.getMessage() );
        }
        SecurityUserDetails userDetails = createUserDetails(user);

        return userDetails;
    }

    /**
      * 构建userdetails
      *
      * @return
      */
    private SecurityUserDetails createUserDetails(User user) {
        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<Role> roleList = roleService.getRoleListByUser(user);

        // 构造security用户
        return SecurityUserDetails.builder()
                .id(user.getId())
                .username(user.getAccount())
                .password(user.getPassword())
                .phone(user.getPhone())
                .enabled(true)
                .accountNonExpired(true)
                .credentialsNonExpired(true)
                .accountNonLocked(true)
                .roles(roleList)
                .build();
    }

}




